// PLC操作Hook，用于基础控制和分组控制面板的复用
import { useState, useCallback } from 'react';
import plcService from '../services/plcService';
import { filterValidVariables, prepareWriteValue, displayReadValue } from '../utils/plcUtils';

/**
 * PLC操作Hook
 * @returns {Object} 包含PLC操作相关状态和方法的对象
 */
export const usePLCOperations = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  /**
   * 读取变量
   * @param {Array} variables 变量数组
   * @param {boolean} isGroup 是否为分组操作
   * @param {string} groupId 分组ID（如果是分组操作）
   * @returns {Promise<Object>} 读取结果
   */
  const handleRead = useCallback(async (variables, isGroup = false, groupId = null) => {
    setLoading(true);
    setError(null);
    
    try {
      console.log('=== 读取操作状态检查 ===');
      console.log('变量列表:', variables);
      console.log('是否分组操作:', isGroup);
      console.log('分组ID:', groupId);
      
      // 过滤出有效的变量地址
      const validVariables = filterValidVariables(variables);
      const varAddresses = validVariables.map(v => v.address);
      
      console.log('过滤后的变量地址:', varAddresses);
      
      // 验证地址列表
      if (varAddresses.length === 0) {
        console.log('警告: 没有有效的变量地址');
        throw new Error('请输入要读取的变量地址');
      }
      
      let result;
      
      if (isGroup && groupId) {
        // 分组读取
        console.log('📤 正在读取分组变量:', groupId);
        result = await plcService.readGroupVariables(groupId);
      } else {
        // 基础读取
        console.log('📤 正在读取变量地址:', varAddresses);
        result = await plcService.readVariables(varAddresses);
      }
      
      console.log('📥 读取结果:', result);
      
      // 确保返回的数据格式一致
      if (result.success) {
        // 直接返回完整的读取结果，包括success状态和values数据
        return result;
      } else {
        const errorMessage = result.error || result.message || '未知错误';
        throw new Error('变量读取失败: ' + errorMessage);
      }
    } catch (err) {
      const errorMessage = err.message || '读取变量时发生未知错误';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 写入变量
   * @param {Array} variables 变量数组
   * @param {boolean} isGroup 是否为分组操作
   * @param {string} groupId 分组ID（如果是分组操作）
   * @returns {Promise<Object>} 写入结果统计
   */
  const handleWrite = useCallback(async (variables, isGroup = false, groupId = null) => {
    setLoading(true);
    setError(null);
    
    try {
      console.log('=== 写入操作状态检查 ===');
      console.log('变量列表:', variables);
      console.log('是否分组操作:', isGroup);
      console.log('分组ID:', groupId);
      
      // 过滤出有效的变量
      const writeVars = filterValidVariables(variables);
      
      console.log('过滤后的写入变量:', writeVars);

      // 检查是否有变量
      if (writeVars.length === 0) {
        throw new Error('请输入要写入的变量地址');
      }

      let successCount = 0;
      let failCount = 0;
      const failedVariables = [];
      
      // 逐个写入变量，提供详细的错误信息
      for (const variable of writeVars) {
        try {
          console.log('📤 正在写入变量:', variable.address, '值:', variable.value);
          // 准备写入值
          const valueToWrite = prepareWriteValue(variable.value);
          
          let result;
          
          if (isGroup && groupId) {
            // 分组写入
            console.log('📤 发送到后端的数据(分组):', { groupId, variableName: variable.address, value: valueToWrite });
            result = await plcService.writeGroupVariable(groupId, variable.address, valueToWrite);
          } else {
            // 基础写入
            console.log('📤 发送到后端的数据(基础):', { address: variable.address, value: valueToWrite });
            result = await plcService.writeVariable(variable.address, valueToWrite);
          }
          
          if (result.success) {
            successCount++;
            console.log('✅ 变量写入成功:', variable.address);
          } else {
            throw new Error(result.error || result.message || '写入失败');
          }
        } catch (err) {
          failCount++;
          const errorMessage = err.message || `写入变量 ${variable.address} 时发生未知错误`;
          console.error(`❌ 写入变量 ${variable.address} 失败:`, errorMessage);
          failedVariables.push({
            address: variable.address,
            name: variable.name || variable.address,
            error: errorMessage
          });
        }
      }

      // 返回结果统计
      return {
        success: failCount === 0,
        successCount,
        failCount,
        total: writeVars.length,
        failedVariables
      };
    } catch (err) {
      const errorMessage = err.message || '写入变量时发生未知错误';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 显示通知消息
   * @param {string} message 消息内容
   * @param {string} type 消息类型 (success, error, info)
   */
  const showNotification = useCallback((message, type = 'info') => {
    const notification = document.createElement('div');
    notification.textContent = message;
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3'};
      color: white;
      padding: 15px;
      border-radius: 5px;
      z-index: 10000;
      box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    `;
    document.body.appendChild(notification);
    setTimeout(() => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    }, 3000);
  }, []);

  return {
    loading,
    error,
    handleRead,
    handleWrite,
    showNotification,
    setLoading,
    setError
  };
};

export default usePLCOperations;